<template>
  <div v-if="visible" class="video-box">
    <div class="close" @click.stop="videoVisibleClose">
      <img src="/img/cockpit/closeBtn.png" alt="" />
    </div>
    <video id="myFlvVideo" muted autoplay controls />
  </div>
</template>
<script setup>
import flvjs from "flv.js";
import {defineEmits, ref, onBeforeUnmount} from "vue"
import {ElMessage} from "element-plus";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits([
  "closeVideoCard",
]);
const flvPlayer = ref(null);
const error = ref(false);
const videoVisibleClose = () => {
  emits("closeVideoCard");
}

const createVideo = (url) => {
  console.log(url)
  if (flvjs.isSupported()) {
    setTimeout(() => {
      var videoElement = document.getElementById('myFlvVideo')
      flvPlayer.value = flvjs.createPlayer(
          {
            type: 'flv',
            url: url,
          },
          {
            cors: true, // 是否跨域
            enableWorker: false, // 是否多线程工作
            enableStashBuffer: false, // 是否启用缓存
            // stashInitialSize: 128, // 缓存大小(kb)  默认384kb
            autoCleanupSourceBuffer: true // 是否自动清理缓存
          }
      )
      flvPlayer.value.attachMediaElement(videoElement)
      flvPlayer.value.load()
      flvPlayer.value.play()
      // 加载完成
      flvPlayer.value.on(flvjs.Events.LOADING_COMPLETE, () => {
        error.value = false;
      });
      // 加载失败
      flvPlayer.value.on(flvjs.Events.ERROR, () => {
        ElMessage.warning({
          message: "视屏加载失败，请检查设备是否连接成功！",
          duration: 2000,
        });
        detachMediaElement();
        error.value = true;
      },(error) => {
        console.log(error.value);
      });
    }, 1000)
  }else {
    error.value = true;
  }
}

const detachMediaElement = () => {
  flvPlayer.value.pause();
  flvPlayer.value.unload();
  flvPlayer.value.detachMediaElement();
  flvPlayer.value.destroy();
  flvPlayer.value = "";
}

onBeforeUnmount(() => {
  detachMediaElement()
})

defineExpose({
  createVideo
})
</script>
<style lang="scss" scoped>
.video-box{
  width: 500px;
  height: 441px;
  position: absolute;
  z-index: 101;
  top: 16%;
  left: 30%;
  border-radius: 4px;
  background-color: rgba(9, 27, 35, 0.8);
  backdrop-filter: blur(5px);
  -webkit-backdrop-filter: blur(5px);
  animation: rotate 3s linear infinite;

  #myFlvVideo {
    border: 1px solid #000;
    width: 100%;
    height: 100%;
  }
  .close {
    width: 49px;
    height: 49px;
    cursor: pointer;
    position: absolute;
    top: 0;
    right: 0;
    z-index: 102;

    img {
      width: 49px;
      height: 49px;
      line-height: 49px;
    }
  }
}
</style>